package com.xxmw.transaction.controller.subscribe;

import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.controller.BaseController;
import com.xxmw.transaction.model.app.Symbol;
import com.xxmw.transaction.model.subscribe.SymbolSub;
import com.xxmw.transaction.service.app.SymbolService;
import com.xxmw.transaction.service.app.SymbolSubService;
import com.xxmw.transaction.service.support.SubscribeWebSocket;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 交易度订阅
 * @author luowenliang
 * @since 2020/2/18 10:54
 */
@Validated
@RestController
@RequestMapping("/admin/symbol/sub")
public class SymbolSubController extends BaseController {

    @Autowired
    private SymbolSubService symbolSubService;

    @Autowired
    private SymbolService symbolService;

    /**
     * 列表获取
     * @param currency
     * @return
     */
    @GetMapping("/list")
    @RequiresPermissions("symbol:sub:list")
    public R list(@RequestParam(value = "currency", defaultValue = "usdt")String currency) {

        List<Symbol> symbols = symbolService.findByQuoteCurrency(currency);

        Map<String, List<SymbolSub>> reMap = new HashMap<>();

        if (null != symbols && !symbols.isEmpty()) {
            for (Symbol symbol : symbols) {
                reMap.put(symbol.getBaseCurrency(), symbolSubService.findBySymbolId(symbol.getId()));
            }
        }

        return R.ok(reMap).put("symbols", symbols);
    }

    /**
     * 获取所有已开启订阅的列表
     * @return
     */
    @GetMapping("/openList/{suffix}")
    public R openList (@PathVariable String suffix) {
        List<SymbolSub> list = symbolSubService.openBrickList(suffix);
        List<String> symbolList = new ArrayList<>();
        Map<String, List<SymbolSub>> bourseMap = new HashMap<>();

        if (null != list && list.size() > 0) {
            symbolList = list.parallelStream().map(SymbolSub::getSymbol).distinct().collect(Collectors.toList());
            bourseMap = list.parallelStream().collect(Collectors.groupingBy(SymbolSub::getSymbol));
        }

        return R.ok().put("symbols", symbolList).put("bourseMap", bourseMap);
    }

    /**
     * 新增订阅
     * @param bourse
     * @param symbol
     * @return
     */
    @PostMapping("/save")
    public R save (@NotNull(message = "交易所不能为空") @RequestParam(value = "bourse") Integer bourse,
                   @NotBlank(message = "交易对不能为空") @RequestParam(value = "symbol") String symbol) {

        Symbol s = symbolService.getBuyName(symbol);

        if (null == s) {
            return R.error("该交易对不存在");
        }

        SymbolSub old = symbolSubService.getByBourseAndSymbol(bourse, symbol);

        if (null != old) {
            return R.error("该交易所已订阅该交易对");
        }
        //新增订阅
        SymbolSub symbolSub = new SymbolSub();
        symbolSub.setSymbolId(s.getId());
        symbolSub.setBourse(bourse);
        symbolSub.setStatus(1);
        symbolSub.setSymbol(symbol);
        symbolSub.setCreated(new Date());
        symbolSubService.save(symbolSub);
        return R.ok();
    }

    /**
     * 订阅/取消订阅
     * @param id
     * @param status 1 订阅   2 取消订阅
     * @return
     */
    @GetMapping("/enable")
    public R cancel(@RequestParam(value = "id") Integer id, @RequestParam(value = "status") Integer status) {
        SymbolSub symbolSub = symbolSubService.getById(id);
        if (!symbolSub.getStatus().equals(status)) {
            symbolSub.setStatus(status);
            symbolSubService.saveOrUpdate(symbolSub);
            //获取websocket对象
            SubscribeWebSocket webSocket = symbolSubService.getWebSocket(symbolSub.getBourse());
            if (webSocket == null) {
                return R.error("websocket 获取失败， 交易所错误");
            }
            Symbol symbol = symbolService.getById(symbolSub.getSymbolId());
            if (symbol == null) {
                return R.error("交易对错误");
            }
            if(status == 1) {
                webSocket.unSubscribe(symbol);
            } else if (status == 2){
                webSocket.subscribe(symbol);
            }
            return R.ok();
        }
        return R.error("状态异常");
    }


    /**
     * 获取所有可搬砖的交易对
     * @return
     */
    @GetMapping("/available")
    public R available () {
        return R.ok(symbolSubService.listByBourse(null));
    }

}
